//
//  UIButton+YGActionBlock.m
//  UIKit分类整合
//
//  Created by Mr.xu on 2017/1/8.
//  Copyright © 2017年 xiaokang100. All rights reserved.
//

#import "UIButton+YGActionBlock.h"
#import <objc/runtime.h>

char * const UIButtonActionBlock = "UIButtonActionBlock";


@implementation UIButton (YGActionBlock)
- (void)performActionBlock {
    dispatch_block_t block = self.actionBlock;
    if (block)
        block();
}

- (dispatch_block_t)actionBlock {
    return objc_getAssociatedObject(self, UIButtonActionBlock);
}

- (void)setActionBlock:(dispatch_block_t)actionBlock {
    
    if (actionBlock != self.actionBlock) {
        [self willChangeValueForKey:@"actionBlock"];
        objc_setAssociatedObject(self, UIButtonActionBlock, actionBlock, OBJC_ASSOCIATION_COPY);
        [self removeTarget:self
                    action:@selector(performActionBlock)
          forControlEvents:UIControlEventTouchUpInside];
        [self addTarget:self
                 action:@selector(performActionBlock)
       forControlEvents:UIControlEventTouchUpInside];
        [self didChangeValueForKey:@"actionBlock"];
    }
}

@end
